package com.qf.openapi.web.master.controller;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import com.qf.openapi.web.master.vo.PageVo;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import com.qf.openapi.web.master.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/currentUser")
    public ResultVo currentUser(HttpSession session){
        // 从session中获取用户信息 ，放入ResultVO返回
        return ResultVo.ok(session.getAttribute(Constants.USER_SESSION_KEY));
    }

    @RequestMapping("/pic")
    public void getUserPic(String picname,HttpServletRequest request,HttpServletResponse response){
        final String realPath = request.getServletContext().getRealPath(Constants.UPLOAD_FILE_PATH);
        // 根据传入的图片文件名，取服务器端指定路径加载图片并返回
        try {
            IOUtils.copy(new FileInputStream(realPath+File.separator+picname),response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResultVo login(String autologin,
                          String username,
                          String password,
                          @RequestParam("capchar") String code,
                          HttpSession session,
                          HttpServletResponse response){
        log.info("接收到参数，username={}，password={}，code={}",username,password,code);
        ResultVo resultVo = null;
        // 1. 处理验证码
        final String captcha = (String) session.getAttribute("captcha");
        if (!code.equals(captcha)){
            log.debug("验证码验证失败，session中的验证码{}，传入的验证码{}",captcha,code);
            // 返回错误消息，验证码错误
            return ResultVo.getInstance(Constants.USER_LOGIN_CAPCHAR_ERROR_CODE,Constants.USER_LOGIN_CAPCHAR_ERROR_MSG);
        }
        // 2. 调用service层方法处理登录
        User user = userService.login(username, password);

        // 3. 封装返回值ResultVo对象
        if (user!=null){
            session.setAttribute(Constants.USER_SESSION_KEY,user);
            if(autologin!=null&&autologin.equals("on")){
                String usertoken = username+"-"+password;
                final Cookie cookie = new Cookie(Constants.USER_AUTOLOGIN_TOKEN, usertoken);
                cookie.setPath("/");
                //以秒为单位：60秒*60分钟*24小时*14天
                cookie.setMaxAge(60*60*24*14);
                response.addCookie(cookie);
            }
            resultVo = ResultVo.ok(user);
        }else {
            // 如果user为空，意味登录失败
            resultVo = ResultVo.fail();
        }
        return resultVo;
    }

    @RequestMapping("/regist")
    @ResponseBody
    public ResultVo regist(UserVo userVo, MultipartFile file1, HttpSession session){
        log.debug("接收参数：userVo={},file1={}",userVo,file1);

        // 1. 处理验证码
        final String captcha = (String) session.getAttribute("captcha");
        final String code = userVo.getCapchar();
        if ( code==null||!(code.equals(captcha))){
            log.debug("验证码校验失败----->sesson中的验证码为{},传入的验证码为{}",captcha,code);
            // 返回错误消息，验证码错误
            return ResultVo.getInstance(Constants.USER_LOGIN_CAPCHAR_ERROR_CODE,Constants.USER_LOGIN_CAPCHAR_ERROR_MSG);
        }

        // 补充校验前台传入的用户名的长度
        final String username = userVo.getName();
        if (username==null || username.equals("")|| username.length()<3){
            return ResultVo.fail();
        }
        final ServletContext servletContext = session.getServletContext();
        final String realPath = servletContext.getRealPath(Constants.UPLOAD_FILE_PATH);
        final File dir = new File(realPath);
        if (!dir.exists()){  // 如果存放文件的目录不存在的话，则创建该目录
            dir.mkdirs();
        }
        ResultVo resultVo = userService.regist(userVo,file1,realPath);
        return resultVo;
    }

    //检验用户名是否存在
    @RequestMapping("/checkusername")
    @ResponseBody
    public ResultVo checkUsername(String username){
        return userService.checkUserName(username);
    }

    //分页查询
    @RequestMapping("/getAllUsers")
    @ResponseBody
    public TableVo<User> getAllUsers(PageVo pageVo,UserVo userVo){
        log.debug("获取参数pageVo={},userVo={}",pageVo,userVo);
        return userService.getAllUsersByPage(pageVo,userVo);
    }


    //添加用户
    @RequestMapping("/add")
    public ResultVo addUser(User user){
        log.debug("获取参数为user={}",user);
        return userService.addUser(user);
    }

    //删除用户
    @RequestMapping("/del")
    public ResultVo delUsers(String[] ids){
        log.debug("获取的id长度为:{}"+ids.length);
        return userService.del(ids);
    }

    //编辑模块
    @RequestMapping("/update")
    public ResultVo updateUser(User user){
        log.debug("获取参数为user={}",user);
        return userService.updateUser(user);
    }

    @RequestMapping("/export")
    @ResponseBody
    public ResultVo export(HttpServletRequest request){
        final ServletContext servletContext = request.getServletContext();
        final String realPath = servletContext.getRealPath(Constants.UPLOAD_FILE_PATH);
        final File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        return userService.exportBatch(realPath);
    }
}
